import React from 'react'
import {StyleSheet, Text, View} from "react-native";
import TimeUtil from "../../utils/TimeUtil";

let countDownInterval;
export default class CountDown extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            count_time: props.countTime ? props.countTime : 0,
        };
    }

    componentDidMount() {
        this._startCountDown();
    }

    componentWillUnmount() {
        this._clearCountDown();
    }

    render() {
        return (
            <View style={Styles.periodsNumber}>
                <View style={{flex: 1}}>
                    <Text>{this.props.leftText}</Text>
                </View>
                <View style={{alignItems: 'flex-end', flexDirection: 'row'}}>
                    <Text>{this.props.rightText}</Text>
                    {this.state.count_time > 0 &&
                    <Text style={{color: '#e31809'}}>{TimeUtil.secondsFormat(this.state.count_time)}</Text>}
                </View>
            </View>
        )
    }

    /**
     * 启动倒计时
     */
    _startCountDown = () => {
        let self = this;
        if (this.state.count_time > 0) {
            countDownInterval = setInterval(function () {
                self.setState({
                    count_time: self.state.count_time - 1,
                });
            }, 1000);
        } else if (countDownInterval) {
            this._clearCountDown();
            this.props.onCountDownOver && this.props.onCountDownOver();
        }
    };

    _clearCountDown = () => {
        clearInterval(countDownInterval);
        countDownInterval = undefined;
    }


}
const Styles = StyleSheet.create({
    periodsNumber: {
        backgroundColor: 'white',
        padding: 10,
        flexDirection: 'row',
        marginBottom: 10,
    },
});